/**
 * Created by leiweibo on 8/14/15.
 */

var app = angular.module('materialcontroller', []);
app.filter('offset', function () {
  return function (input, start) {
    start = parseInt(start, 10);
    return input.slice(start);
  };
});

app.controller('MaterialCtrl', function ($scope, $window, $compile, BaseService, MaterialService, MaterialData) {

  $scope.role = $window.sessionStorage.role;
  $scope.clearEditor = function () {
    $scope.editor = '';
  };

  $scope.callServer = function (tableState) {
    $scope.isLoading = true;

    var pagination = tableState.pagination;
    var pageSize = pagination.number || 20;
    var pageNo = Math.ceil((pagination.start + 1) / pageSize) || 1;

    MaterialService.list(pageNo, pageSize, tableState, function(res) {
      $scope.displayed = res.materials;
      tableState.pagination.numberOfPages = res.pageCount;
      $scope.isLoading = false;
    });
  };

  $scope.dtl = function(pos) {
    var targetMaterial = $scope.displayed[pos];
    MaterialData.set(targetMaterial);
    window.location = "#/material_dtl/" + targetMaterial._id;
  }

  $scope.add_material = function() {
    MaterialData.set(null);
    window.location = '#/create_material';
  }



  $scope.edit = function(pos) {
    MaterialData.set($scope.displayed[pos]);
    window.location = "#/update_material";
  }

  if (MaterialData.get() && !$.isEmptyObject(MaterialData.get())) {
    var data = MaterialData.get();
    $scope.id = data._id;
    $scope.title = data.title;
    $scope.author = data.author;
    $scope.content = data.content;
    $scope.update_time = data.update_time;
    $scope.attachments = data.attachments;
  }

  $scope.delete = function (pos) {
    bootbox.setDefaults("locale", "zh_CN");
    bootbox.confirm("确定删除吗", function (result) {
      if (result == true) {
        var material = $scope.displayed[pos];
        if (material) {
          var data = {id: material._id};
          MaterialService.delete(data, function (res) {
            if (res.result == true) {
              $scope.displayed.splice(pos, 1);
            } else {
              alert('删除数据失败');
            }
          }, function (data, status) {
          });
        } else {
          alert("请刷新重试");
        }
      }
    });
  };

  var constructObj = function(arr, descArr) {
    var result = new Array();
    for (var i = 0; i < arr.length; i++) {
      if (descArr[i] && arr[i]) {
        var attachment = new Attachment(descArr[i], arr[i]);
        result.push(attachment);
      }
    }
    return result;
  }

  $scope.createOrUpdate = function() {

    if($scope.attachments.length < $scope.attachment_desc.length) {
      alert('附件未上传或者上传未完成');
      return;
    }

    var formData = {
      id: $scope.id,
      title: $scope.title,
      content: $scope.content,
      author: $window.sessionStorage.userid,
      attachments: constructObj($scope.attachments, $scope.attachment_desc)
    };

    if ($scope.id) {
      MaterialService.update(formData, function (res) {
        if (res.result == true) {
          window.location = "#/material_list";
        } else {
          $scope.error_msg = res.message;
        }
      }, function (data, status) {
        if (status == 403) {
          $scope.error_msg = '无权限进行此操作';
        }

      })
    } else {
      MaterialService.create(formData, function(res) {
        if (res.result == true) {
          alert('创建内容成功');
          $scope.content = '',
          delete $scope.title,
          $scope
          $scope.attachment_desc.length = 0,
          $scope.attachments.length = 0,
          $('div[id^=attachment_grp_]').remove()
        } else {
          $scope.error_msg = res.message;
        }
      }, function(data, status) {
        $scope.error_msg = '无权限进行此操作';
      })
    }
  }



  $scope.add = function() {
    MaterialData.set(null);
    window.location = "#/create_hospital";
  };

  $scope.attachments = [];
  $scope.attachment_desc = [];
  $scope.count = 0;

  $scope.addAttachment = function(event) {
    addItem(event, 'attachments', $scope.attachments, $scope.count);
    $scope.count += 1;
  }

  var addItem = function(event, arrayStr, array, count) {
    var queryStr = "div[id^=attachment_grp]";
    console.log($(queryStr).length);
    if ($(queryStr).length > 3) {
      alert('最多不能超过3个上传')
      return;
    }

    var content = $('#attachment_grp').clone();
    $(content).removeClass('hidden');
    $(content).attr('id', 'attachment_grp_' + count);
    $(content).find('#attachment').attr('ng-model', 'attachment_desc[' + count+ "]").attr('required', true);
    $(content).find('#container_attachment_0').attr('id', 'container_attachment_' + count);
    $(content).find('#browser_attachment_0').attr('id', 'browser_attachment_' + count);
    $(content).find('div[id^=percentage_]').text('');
    $(content).find('div[id^=percentage_]').attr('id', 'percentage_' + count);
    $(content).find('a').last().parent().attr('ng-click', "deleteItem($event," + count +  ")");

    var compiledContent = $compile(content)($scope);
    $('#attachment_grp').before(compiledContent);

    BaseService.getBaseUploader(array, 'browser_attachment_' + count, 'container_attachment_'  + count, 'percentage_' + count, count);
  };

  $scope.deleteItem = function(event, index) {
    $scope.attachments.splice(index, 1);
    $('#attachment_grp_' + index).remove();
    delete $scope.attachment_desc[index];
  }

  var Attachment = function(desc, url) {
    this.url = url;
    this.desc = desc;
  }

});